"""
定时任务管理API路由
提供定时任务系统的RESTful API接口
"""

from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Body
from sqlalchemy.orm import Session

from src.config.database import get_db
from src.models.scheduled_task import (
    ScheduledTaskCreate, 
    ScheduledTaskUpdate, 
    ScheduledTaskResponse,
    TaskExecutionHistoryResponse
)
from src.services.scheduler_service import SchedulerService
from src.utils.logging import get_logger

logger = get_logger(__name__)

router = APIRouter(prefix="/scheduled-tasks", tags=["scheduled_tasks"])

# 初始化服务
scheduler_service = SchedulerService()


@router.post("", response_model=ScheduledTaskResponse)
async def create_scheduled_task(
    task_data: ScheduledTaskCreate,
    db: Session = Depends(get_db)
):
    """创建定时任务"""
    try:
        task = scheduler_service.create_task(db, task_data.dict())
        if not task:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="创建定时任务失败"
            )
        return ScheduledTaskResponse.from_orm(task)
    except Exception as e:
        logger.error(f"创建定时任务失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建定时任务失败"
        )


@router.get("", response_model=List[ScheduledTaskResponse])
async def list_scheduled_tasks(
    enabled_only: bool = False,
    db: Session = Depends(get_db)
):
    """获取定时任务列表"""
    try:
        tasks = scheduler_service.list_tasks(db, enabled_only=enabled_only)
        return [ScheduledTaskResponse.from_orm(task) for task in tasks]
    except Exception as e:
        logger.error(f"获取定时任务列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取定时任务列表失败"
        )


@router.get("/{task_id}", response_model=ScheduledTaskResponse)
async def get_scheduled_task(
    task_id: str,
    db: Session = Depends(get_db)
):
    """获取定时任务详情"""
    try:
        task = scheduler_service.get_task(db, task_id)
        if not task:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="定时任务不存在"
            )
        return ScheduledTaskResponse.from_orm(task)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取定时任务详情失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取定时任务详情失败"
        )


@router.put("/{task_id}", response_model=ScheduledTaskResponse)
async def update_scheduled_task(
    task_id: str,
    task_data: ScheduledTaskUpdate,
    db: Session = Depends(get_db)
):
    """更新定时任务"""
    try:
        success = scheduler_service.update_task(db, task_id, task_data.dict(exclude_unset=True))
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="定时任务不存在"
            )
        
        task = scheduler_service.get_task(db, task_id)
        return ScheduledTaskResponse.from_orm(task)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新定时任务失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新定时任务失败"
        )


@router.delete("/{task_id}")
async def delete_scheduled_task(
    task_id: str,
    db: Session = Depends(get_db)
):
    """删除定时任务"""
    try:
        success = scheduler_service.delete_task(db, task_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="定时任务不存在"
            )
        return {"message": "定时任务删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除定时任务失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除定时任务失败"
        )


@router.post("/{task_id}/toggle")
async def toggle_scheduled_task(
    task_id: str,
    db: Session = Depends(get_db)
):
    """启用/禁用定时任务"""
    try:
        task = scheduler_service.get_task(db, task_id)
        if not task:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="定时任务不存在"
            )
        
        # 切换启用状态
        new_status = not task.enabled
        success = scheduler_service.update_task(db, task_id, {"enabled": new_status})
        if not success:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="更新定时任务状态失败"
            )
        
        return {
            "message": f"定时任务已{'启用' if new_status else '禁用'}",
            "enabled": new_status
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"切换定时任务状态失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="切换定时任务状态失败"
        )


@router.get("/{task_id}/history", response_model=List[TaskExecutionHistoryResponse])
async def get_task_execution_history(
    task_id: str,
    limit: int = 10,
    db: Session = Depends(get_db)
):
    """获取任务执行历史"""
    try:
        history = scheduler_service.get_execution_history(db, task_id, limit)
        return [TaskExecutionHistoryResponse.from_orm(record) for record in history]
    except Exception as e:
        logger.error(f"获取任务执行历史失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取任务执行历史失败"
        )